/**
 * asciily datagram tools
 */
(function() {

	NONCE_SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	datagram = {
		genNonce : function() {
			var nonce = new Array();
			for (var i = 0; i < 32; i++) {
				var index = Math.floor((Math.random() * 32) + 1);
				nonce.push(NONCE_SYMBOLS.charAt(index))
			}
			return nonce.toString().replace(/,/g, "");
		},
		genTripleDesKey : function(nonce) {
			if (typeof nonce == "undefined" || nonce == null) {
				return undefined;
			}
			if (nonce.length < 24) {
				return undefined;
			}
			var tempA = new Array(), tempB = new Array();
			for (var i = 0; i < nonce.length; i++) {
				if (i % 2 == 1) {
					tempA.push(nonce.charAt(i));
				} else {
					tempB.push(nonce.charAt(i));
				}
			}
			for (var i = 0; i < tempB.length; i++) {
				if (i % 2 == 0) {
					tempA.push(tempB.slice(i, i + 1));
				}
			}
			var a = tempA.slice(1, 2);
			var b = tempA.slice(9, 10);
			var c = tempA.slice(6, 7);
			var d = tempA.slice(23);
			var e = tempA.slice(11, 12);
			var f = tempA.slice(19, 20);

			tempA.splice(1, 1, b);
			tempA.splice(9, 1, a);
			tempA.splice(6, 1, d);
			tempA.splice(23, 1, c);
			tempA.splice(11, 1, f);
			tempA.splice(19, 1, e);
			return tempA.toString().replace(/,/g, "");
		},
		genMd5Key : function(nonce) {
			if (typeof nonce == "undefined" || nonce == null) {
				return undefined;
			}
			var tempA = new Array();
			for (var i = 0; i < nonce.length; i++) {
				if (i % 2 == 0) {
					tempA.push(nonce.charAt(i));
				}
			}
			return tempA.reverse().toString().replace(/,/g, "");
		},
		md5 : function(string) {
			if (typeof nonce == "undefined" || nonce == null) {
				return undefined;
			}
			return CryptoJS.MD5(string);
		},
		des3Encrypt : function(key, string) {
			if (typeof key == "undefined" || key == null) {
				return undefined;
			}
			if (typeof string == "undefined" || string == null) {
				return undefined;
			}
			var keyHex = CryptoJS.enc.Utf8.parse(key);
			var cipher = CryptoJS.TripleDES.encrypt(string, keyHex, {
				mode : CryptoJS.mode.ECB,
				padding : CryptoJS.pad.Pkcs7
			});
			return CryptoJS.enc.Base64.stringify(cipher.ciphertext);
		},
		des3Decrypt : function(key, string) {
			if (typeof key == "undefined" || key == null) {
				return undefined;
			}
			if (typeof string == "undefined" || string == null) {
				return undefined;
			}
			var keyHex = CryptoJS.enc.Utf8.parse(key);
			var decrypted = CryptoJS.TripleDES.decrypt({
				ciphertext : CryptoJS.enc.Base64.parse(string)
			}, keyHex, {
				mode : CryptoJS.mode.ECB,
				padding : CryptoJS.pad.Pkcs7
			});
			return decrypted.toString(CryptoJS.enc.Utf8);
		},
	};
})();
